<template>
  <div id="myCanvasContent" :style="contentStyle">
    <canvas id="myCanvas" :width="CanvasWidth" :height="CanvasHeight"></canvas>
  </div>
</template>

<script>
/*  {
          pic: "resource/2020/9/9/0f6nsqcqlhC90tFzrWf7rx00-37eok4vczRzEgWaMfhAsnb00"
          resultRegion: "{"frameInfo":"[{\"prob\":0.700331,\"obj_id\":20001,\"w\":586,\"x\":1300,\"h\":639,\"typeName\":\"人员\",\"y\":29,\"hitUrl\":\"\"}]","imageInfo":{"width":"1920","pic":"resource/2020/9/9/0f6nsqcqlhC90tFzrWf7rx00-37eok4vczRzEgWaMfhAsnb00","height":"1080"}}"
          setTime: "2020-09-09 11:23:05"
        } */
export default {
  props: {
    transAiPicToBase64: Function,
    drawData: {
      default() {
        return {}
      },
    },
  },
  data() {
    return {
      picObj: {}, // 服务端传来的图片对象
      frameArr: [], // 画框的集合
      CanvasWidth: 1500,
      CanvasHeight: 100,
      zoomIndex: 1, // 默认不缩放，超过区域就缩放
      base64Data: '',
    }
  },
  computed: {
    contentStyle() {
      return {
        width: this.CanvasWidth + 'px',
        height: this.CanvasHeight + 'px',
      }
    },
  },
  created() {
    let resultRegion = this.drawData.resultRegion
    if (resultRegion) {
      resultRegion = JSON.parse(resultRegion)
      this.picObj = resultRegion.imageInfo
      if (
        !resultRegion.frameInfo ||
        !this.picObj.width ||
        !this.picObj.height
      ) {
        this.base64Data = resultRegion.imageInfo.pic
        return
      }
      this.frameArr = JSON.parse(resultRegion.frameInfo)
      if (resultRegion.region) {
        this.regionArr = resultRegion.region.split(';').map((n) => {
          return JSON.parse(n)
        })
      }
      // this.regionArr=[{"x":1062,"y":221},{"x":590,"y":1076},{"x":1248,"y":1043},{"x":1268,"y":214}]
      this.picObj.width = parseInt(this.picObj.width)
      this.picObj.height = parseInt(this.picObj.height)
      this.$nextTick(() => {
        this.imageLoad()
      })
    }
  },
  methods: {
    // 底图加载完成后
    imageLoad() {
      const that = this
      // 给图片一个合适的容器
      that.zoomIndex = that.CanvasWidth / that.picObj.width
      that.CanvasHeight = that.zoomIndex * that.picObj.height
      that.$nextTick(() => {
        // 在canvas上绘制红框
        that.drawCanvas()
      })
    },
    drawCanvas() {
      const that = this
      //  获取canvas
      that.canvas = document.getElementById('myCanvas')
      //  由于弹窗，确保已获取到
      that.ctx = that.canvas.getContext('2d')
      //  绘制图片 （注意：这里不必把canvas绘制出来，有一个底图image显示就够了）
      let img = new Image() //创建新的图片对象
      img.setAttribute('crossOrigin', 'anonymous')
      img.src = that.picObj.pic
      img.onload = () => {
        that.ctx.drawImage(img, 0, 0, that.CanvasWidth, that.CanvasHeight)
        that.regionArr &&
          that.regionArr.forEach((n) => {
            that.drawRegion(n)
          })
        // 在canvas上绘制红框
        that.drawRecRed()
      }
      img.onerror = () => {
        this.base64Data = this.picObj.pic
      }
    },
    // 画红框
    drawRecRed() {
      const that = this
      /* [{"prob":0.700331,"obj_id":20001,"w":586,"x":1300,"h":639,"typeName":"人员","y":29,"hitUrl":""}] */
      if (that.frameArr.length > 0) {
        let c = document.getElementById('myCanvas')
        let ctx = c.getContext('2d')
        ctx.strokeStyle = 'red'
        ctx.lineWidth = 1
        ctx.font = '20px Georgia'
        ctx.fillStyle = 'red'
        // 循环红框和文字
        that.frameArr.forEach((item) => {
          let x = (item.x || 0) * that.zoomIndex
          let y = (item.y || 0) * that.zoomIndex
          let w = (item.w || 0) * that.zoomIndex
          let h = (item.h || 0) * that.zoomIndex
          // 文字的起点是左下
          if (item.w && item.h) {
            // 绘制矩形
            ctx.strokeRect(x, y, w, h)
            // c. 文字+图像，文字超过顶，文字放到框下方
            if (y < 25) {
              y = y + h + 20
            }
            // b. 文字+图像，默认文字在框上
            else {
              y -= 5
            }
            // d. 文字+图像，文字超过右侧，文字右对齐
            let textW = (item.typeName || '').length * 20
            let rDistance = that.CanvasWidth - x
            if (rDistance < textW) {
              x = x + w - textW
            }
          } else {
            // a. 只有文字，放到左上角
            x = 10
            y = 25
          }
          // 绘制的文字
          ctx.fillText(item.typeName || '', x, y)
        })
      }
      that.base64Data = that.canvas
        .toDataURL('image/jpg')
        .replace('image/jpg', 'image/octet-stream')
    },
    // 画蓝框区域
    drawRegion(arr) {
      let c = document.getElementById('myCanvas')
      let ctx = c.getContext('2d')
      ctx.strokeStyle = 'blue'
      ctx.lineWidth = 4
      arr.forEach((item, i) => {
        let x = (item.x || 0) * this.zoomIndex
        let y = (item.y || 0) * this.zoomIndex
        if (i == 0) {
          ctx.moveTo(x, y)
        } else {
          ctx.lineTo(x, y)
          if (i == arr.length - 1) {
            ctx.lineTo(arr[0].x * this.zoomIndex, arr[0].y * this.zoomIndex)
          }
        }
      })
      ctx.stroke()
    },
  },
  watch: {
    base64Data: {
      handler: function (val) {
        val && this.transAiPicToBase64(val)
      },
    },
  },
}
</script>

<style scoped>
#myCanvasContent {
  visibility: hidden;
  position: relative;
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}
canvas {
  z-index: 1;
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}
</style>
